﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using static System.Threading.Thread;
using static System.Console;
using KongMing.Common;

namespace TaskUnitProject
{
    /// <summary>
    /// 2. 线程阻塞
    /// Task.WaitAll(new Task[] {task1, task2}):等待所有线程执行完成,
    /// Task.WaitAny(new Task[] {task1, task2}):等待任何一个线程完成.
    /// Task.WhenAll().ContinueWith(t=>{}):等待所有线程完成后执行后续操作
    /// Task.WhenAny().ContinueWith(t=>{}):等待任何一个线程完成后执行后续操作
    /// Task.Factory.ContinueWhenAll/Any(new Task[] {task1, task2}, t => { });
    /// </summary>
    public class TaskUnit_1_2:UnitBase
    {
        public static void Go()
        {
            Task task1=new Task(() =>
            {
                SleepSeconds(5);
                WriteLine($"task1执行完毕！,id:{CurrentThread.ManagedThreadId}");
            });
            task1.Start();
            Task task2 = new Task(() => {
                SleepSeconds(2);
                WriteLine($"task2执行完毕！id:{CurrentThread.ManagedThreadId}");
            });
            task2.Start();
            //Task.WaitAll(new Task[]{task1, task2});
            Task.WaitAny(new Task[] {task1, task2});
            WriteLine("主线程执行");


            Task.Factory.ContinueWhenAll(new Task[] {task1, task2}, t => { });
            //Task.WhenAll().ContinueWith(t=>{}); 
            Task.WhenAny(new Task[] {task1, task2}).ContinueWith(t =>
            {
                SleepSeconds(1);
                WriteLine($"线程延续执行完成！,id:{CurrentThread.ManagedThreadId}");
            });
            WriteLine("主线程执行完成");
        }

    }
}
